/*
 * @Author: i@rysa.cn
 * @Date: 2022-05-14 16:05:33
 * @LastEditTime: 2022-05-14 16:06:45
 * @LastEditors: i@rysa.cn
 * @Description:
 * @FilePath: \go-utils\wechat\mini\sns\login.go
 */
package sns

import (
	"encoding/json"
	"fmt"

	"gitee.com/rysa/go-utils/request"
	"gitee.com/rysa/go-utils/wechat/mini/config"
	"gitee.com/rysa/go-utils/wechat/mini/params"
)

type sns struct {
	*config.MiniConfig
}

func NewSns(cfg *config.MiniConfig) *sns {
	return &sns{cfg}
}

func (s *sns) Login(code string) params.Code2Session {
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", s.Appid, s.AppSecret, code)
	req := request.NewRequest()
	res, err := req.Get(url)
	if err != nil {
		return params.Code2Session{
			Errcode: -1,
			Errmsg:  "网络错误，请稍后重试",
		}
	}
	var rs params.Code2Session
	err = json.Unmarshal(res.Body(), &rs)
	if err != nil {
		return params.Code2Session{
			Errcode: -1,
			Errmsg:  "网络错误，请稍后重试",
		}
	}
	return rs
}
